<template>
  <div class="score-analysis" ref="fullscreenElement">
    <div class="header">
      <h3>{{ title }}</h3>
      <p>
        <b @click="toggleFullscreen"><img src="../../assets/image/qp.png" alt="">{{ isFullscreen ? "退出全屏" : "全屏(F11)"
          }}</b>
        <!-- <em @click="addwebbard">进入讲评</em> -->
      </p>
    </div>
    <div style="height:48px;"></div>
    <!-- 固定在顶部的查询条件 -->
    <!-- <div class="query-section">
        <div class="query-form">
          <el-form :inline="true">
            <el-form-item label="考试ID">
              <el-input v-model="examId" placeholder="请输入考试ID" />
            </el-form-item>
            <el-form-item label="班级ID">
              <el-input v-model="classId" placeholder="请输入班级ID" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div> -->
    <!-- 内容区域，添加上边距以避免被固定查询条件遮挡 -->
    <!-- 成绩概览 -->
    <h3 class="scoreStateTitle">成绩总览 </h3>
    <div class="content-section">
      <div class="searchbox">
        <div class="searchbox-left">
          <div>
            作业：
            <el-select v-model="examId" placeholder="请选择" @change="chooseclassbox">
              <el-option v-for="item in homeworksavelist" :key="item.examId" :label="item.examName"
                :value="item.examId">
              </el-option>
            </el-select>
          </div>
          <div>
            选择日期：
            <el-date-picker v-model="dataTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" @change="datapickerbox">
            </el-date-picker>
          </div>
        </div>
        <div class="classboxcitybox">
          班级2：
          <div style="display: flex;align-items: center;">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
              style="margin-right:15px;margin-left:5px;">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="classIds1" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in classlistbox" :label="city.classId" :key="city.classId">{{ city.className
              }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <score-overview :exam-id="examId" :class-ids="classids" :class-ids1="classIds1" ref="scoreOverviewRef"
        v-if="examId && classids" />

      <!-- 分数分布 -->
      <score-distribution :exam-id="examId" :class-ids="classids" :grade-id="gradeId" :subject-id="subjectId"
        :class-ids1="classIds1" ref="scoreDistributionRef" v-if="examId && classids" />

      <!-- 作业分析 -->
      <homework-analysis :exam-id="examId" :class-ids="classids" :class-ids1="classIds1" :examName="examName"
        ref="homeworkAnalysisRef" v-if="examId && classids" />
    </div>
    <div class="leftbarcontent">
      <div class="zdbutton" @click="toolhidden" :class="{ 'zdbutton-visible': !isToolShowVisible }"></div>
      <ul class="leftbar" :class="{ 'toolshow-visible': isToolShowVisible }">
        <li v-for="(group, index) in menuGroups" :key="index">
          <template v-if="group.title">
            <span>{{ group.title }}</span>
          </template>
          <a v-for="(item, i) in group.items" :key="i" href="#" @click.prevent="selectMenuItem(item.id)"
            :class="{ 'active': selectedItem === item.id }">
            {{ item.text }}
          </a>
        </li>
      </ul>
      <!-- <ul class="leftbar" :class="{ 'toolshow-visible': isToolShowVisible }">
              <li>
                  <span>成绩总览</span>
                  <a href="#" @click="scrollToSection('#High-frequency-incorrect-questions')">高频错题</a>
                  <a href="#" @click="scrollToSection('#Homework-score')">作业得分表</a>
                  <a href="#" @click="scrollToSection('#fluctuate-student')">上升/下降学生</a>
              </li>
              <li>
                  <span>成绩概览</span>
                  <a href="#" @click="scrollToSection('#fractional-distribution')">分数段分布图表表格</a>
                  <a href="#" @click="scrollToSection('#Two-point-five-rate')">两分五率/排名</a>
                  <a href="#" @click="scrollToSection('#student-distribution')">提交率对比</a>
                  <a href="#" @click="scrollToSection('#student-distribution')">学优生/学困生分布</a>
              </li>
              <li>
                  <span>作业分析</span>
                  <a href="#" @click="scrollToSection('#Homework-quality')">作业质量</a>
                  <a href="#" @click="scrollToSection('#Test-score-rate')">试题得分率</a>
                  <a href="#" @click="scrollToSection('#Test-knowledge-rate')">知识点得分率</a>
                  <a href="#" @click="scrollToSection('#Small-question-analysis')">小题分析</a>
                  <a href="#" @click="scrollToSection('#Objective-Question-Answering')">客观题作答分布</a>
                  <a href="#" @click="scrollToSection('#subjective-Question-Answering')">主观题作答分布</a>
              </li>
          </ul> -->
    </div>

  </div>
</template>

<script>
import ScoreOverview from './components/grade/scoreoverview.vue'
import ScoreDistribution from './components/grade/scoreDistribution.vue'
import HomeworkAnalysis from './components/grade/homeworkanalysis.vue'
import { homeworkDate } from '@/api/grade'

export default {
  name: 'ScoreAnalysis',
  components: {
    ScoreOverview,
    ScoreDistribution,
    HomeworkAnalysis
  },
  data () {
    return {
      examId: '',
      classId: '',
      showComponents: false,
      isToolShowVisible: true,
      isFullscreen: false, // 当前是否处于全屏状态
      checkAll: false,
      classIds1: [],
      cities: ['1', '2', '3', '4'],
      isIndeterminate: false,
      value1: '',
      options: [],
      value: '',
      title: '',
      subjectId: 0,
      gradeId: 0,
      classids: null,
      startTime: '',
      endTime: '',
      homeworksavelist: [],
      classlistbox: [],
      dataTime: null,
      examName: '',
      selectedItem: 'Homework-score',
      menuGroups: [
        {
          title: '成绩总览',
          items: [
            // { id: 'High-frequency-incorrect-questions', text: '高频错题' },
            { id: 'Homework-score', text: '成绩单' },
            { id: 'fluctuate-student', text: '原始分成绩及排名' }
          ]
        },
        {
          title: '成绩概览',
          items: [
            { id: 'fractional-distribution', text: '分数段分布图表表格' },
            { id: 'Two-point-five-rate', text: '两分五率/排名' },
            { id: 'student-distribution', text: '提交率对比' },
            { id: 'student-distribution1', text: '学优生/学困生分布' }
          ]
        },
        {
          title: '作业分析',
          items: [
            { id: 'Homework-quality', text: '作业质量' },
            { id: 'Test-score-rate', text: '试题得分率' },
            { id: 'Test-knowledge-rate', text: '知识点得分率' },
            { id: 'Small-question-analysis', text: '小题分析' },
            { id: 'Objective-Question-Answering', text: '客观题作答分布' },
            { id: 'subjective-Question-Answering', text: '主观题作答分布' }
          ]
        }
      ],
    }
  },
  methods: {
    selectMenuItem (itemId) {
      this.selectedItem = itemId;
      // 这里可以添加你的滚动逻辑
      this.scrollToSection(`#${itemId}`);
    },
    chooseclassbox (val) {
      // alert(val)
      console.info(val)
      let list = this.homeworksavelist.filter(item => item.examId == val)
      this.classlistbox = list[0].classInfoList
      this.examName = list[0].examName
    },
    async homeworkdataapi () {
      this.homeworksavelist = []
      this.classlistbox = []
      this.examId = ''
      try {
        const res = await homeworkDate(
          Number(this.subjectId),
          Number(this.gradeId),
          String(this.classids),
          String(this.startTime),
          String(this.endTime)
        )
        // console.log('res 是否是 Promise:', res); // 应该是 false
        if (res.code === 200) {
          this.homeworksavelist = res.data
          this.classlistbox = res.data[0].classInfoList
          this.examName = res.data[0].examName
          // this.classIds1 = res.data[0].classInfoList.map(item => item.classId)
          this.classIds1 = res.data[0].classInfoList.map(item => item.classId)
          this.classids = res.data[0].classInfoList.map(item => item.classId).join(',')
          this.checkAll = this.classIds1.length === this.classlistbox.length;
          this.examId = res.data[0].examId
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    datapickerbox (val) {
      if (!val || val.length !== 2) return;

      // 获取开始日期和结束日期（Date 对象）
      const [start, end] = val;

      // 格式化为 YYYY-MM-DD
      this.startTime = this.formatDate(start);
      this.endTime = this.formatDate(end);

      this.homeworkdataapi()
    },
    // 辅助方法：格式化日期为 YYYY-MM-DD
    formatDate (date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleCheckAllChange (val) {
      // 获取所有班级ID，并进行去重处理
      const allClassIds = val ? this.classlistbox.map(item => item.classId) : [];
      const uniqueClassIds = [...new Set(allClassIds)];

      this.classIds1 = uniqueClassIds;
      this.classids = uniqueClassIds.join(',');
      this.isIndeterminate = false;

      // 调试信息：打印传给后台的参数
      console.log('全选变化 - examId:', this.examId);
      console.log('全选变化 - classIds:', this.classids);
      console.log('全选变化 - classIds1:', this.classIds1);
      console.log('全选变化 - val参数:', val);
      console.log('全选变化 - 原始classIds:', allClassIds);
      console.log('全选变化 - 去重后classIds:', uniqueClassIds);

      // 防御性检查
      if (!this.examId) {
        console.warn('examId 为空，可能导致API请求失败');
      }

      // 检查是否有重复值被移除
      if (allClassIds.length !== uniqueClassIds.length) {
        console.warn('发现重复的班级ID，已自动去重:',
          '原始:', allClassIds,
          '去重后:', uniqueClassIds
        );
      }
    },
    handleCheckedCitiesChange (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.classlistbox.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.classlistbox.length;

      // 重复校验：去除重复的classId
      const uniqueValue = [...new Set(value)];

      // 确保 classIds1 和传入的 value 保持同步，并去重
      this.classIds1 = uniqueValue;

      // 更新classids - 确保与全选时的格式一致
      this.classids = uniqueValue.join(',');

      // 调试信息：打印传给后台的参数
      console.log('单选变化 - examId:', this.examId);
      console.log('单选变化 - classIds:', this.classids);
      console.log('单选变化 - classIds1:', this.classIds1);
      console.log('单选变化 - 原始value:', value);
      console.log('单选变化 - 去重后value:', uniqueValue);

      // 防御性检查：确保 examId 存在
      if (!this.examId) {
        console.warn('examId 为空，可能导致API请求失败');
      }

      // 防御性检查：确保至少选中一个班级
      if (uniqueValue.length === 0) {
        console.warn('没有选中任何班级，classids 为空字符串');
      }

      // 检查是否有重复值被移除
      if (value.length !== uniqueValue.length) {
        console.warn('发现重复的班级ID，已自动去重:',
          '原始:', value,
          '去重后:', uniqueValue
        );
      }
    },
    scrollToSection (selector) {
      this.$nextTick(() => {
        const target = document.querySelector(selector);
        if (target) {
          target.scrollIntoView({ behavior: 'smooth' }); // 平滑滚动
        } else {
          console.warn(`Element with selector "${selector}" not found`);
        }
      });
    },

    toolhidden () {
      this.isToolShowVisible = !this.isToolShowVisible; // 切换抽屉状态
    },// 切换全屏
    toggleFullscreen () {
      if (!document.fullscreenEnabled) {
        alert("您的浏览器不支持全屏功能！");
        return;
      }

      if (this.isFullscreen) {
        // 退出全屏
        document.exitFullscreen();
        this.$refs.fullscreenElement.style.overflow = 'auto';
      } else {
        // 进入全屏
        this.$refs.fullscreenElement.requestFullscreen();
        this.$refs.fullscreenElement.style.overflow = 'auto';
      }
    },
    // 处理全屏状态变化
    handleFullscreenChange () {
      this.isFullscreen = !!document.fullscreenElement;
    },

  },
  created () {

    // this.checkedCities = this.$route.query.classids.split(',')
  },
  mounted () {
    // 监听全屏状态变化
    document.onfullscreenchange = this.handleFullscreenChange;
    // 获取具体参数
    // this.$nextTick(() => {

    // })
    this.title = decodeURIComponent(this.$route.query.title || '')
    this.subjectId = Number(this.$route.query.subjectid) || 0
    this.gradeId = Number(this.$route.query.gradeid) || 0
    // this.classids = this.$route.query.classids || ''
    // this.classIds1 = (this.$route.query.classids || '').split(',').map(Number)
    this.startTime = this.$route.query.startTime || ''
    this.endTime = this.$route.query.endTime || ''
    this.dataTime = [this.startTime, this.endTime]
    this.homeworkdataapi()
  },

}
</script>

<style scoped>
.searchbox {
  background: #fff;
  border-radius: 10px 10px 0 0;
  padding: 24px 24px 0;
  font-size: 14px;
}

.searchbox-left {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.searchbox-left>>>.el-input__inner {
  height: 35px;
  font-size: 12px;
}

.searchbox-left>>>.el-range-input {
  font-size: 12px;
}

.searchbox-left>>>.el-range-separator {
  height: 35px;
  width: 20px;
  font-size: 12px;
  line-height: 35px;
}

.searchbox-left>>>.el-input__icon {
  line-height: 35px;
}

.searchbox-left>>>.el-date-editor .el-range__icon {
  line-height: 30px;
}

.classboxcitybox {
  display: flex;
  align-items: center;
  padding-top: 10px;
}

.classboxcitybox>>>.el-checkbox__label {
  padding-left: 5px;
  font-size: 12px;
}

.classboxcitybox>>>.el-checkbox {
  margin-right: 15px;
}

.score-analysis {
  /* 移除原有内边距 */
  width: 100%;
  background: #F4F7FD;
  padding-bottom: 24px;
  scroll-margin-top: 20px;
}

.header {
  height: 48px;
  background: #4985FF;
  box-shadow: 0 2px 10px 0 #00000080;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  background: #2379F6;
  font-size: 16px;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  z-index: 100;
}

.header h3 {
  font-weight: normal;
  font-size: 16px;
}

.header p {
  display: flex;
}

.header p b {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 134px;
  height: 32px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 17px;
  border: 1px solid #FFFFFF;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  margin-right: 14px;
  font-weight: normal;
}

.header p b img {
  width: 16px;
  margin-right: 8px;
}

.header p em {
  display: inline-block;
  width: 108px;
  height: 32px;
  background: #FFFFFF;
  border-radius: 17px;
  border: 1px solid #FFFFFF;
  color: #2379F6;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  font-style: normal;
}

/* 固定在顶部的查询条件 */
.query-section.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px 20px;
}

/* 内容区域添加上边距，避免被固定查询条件遮挡 */
.content-section {
  box-sizing: border-box;
  margin: 0px 140px 0;
  /* 根据查询条件的高度调整 */
}

.scoreStateTitle {
  font-size: 18px;
  color: #295CFF;
  line-height: 45px;
  margin: 0 140px;
  font-weight: normal;
  position: relative;
  padding-left: 25px;
  font-weight: bold;
}

.scoreStateTitle:after {
  content: '';
  width: 14px;
  height: 14px;
  opacity: 0.5;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 0;
  top: 15px;
}

.scoreStateTitle::before {
  content: '';
  width: 8px;
  height: 8px;
  opacity: 0.2;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 10px;
  top: 23px;
}

.query-section {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.query-form {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 适配移动端 */
@media screen and (max-width: 768px) {
  .query-form {
    flex-direction: column;
    align-items: stretch;
  }

  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .content-section {
    margin-top: 160px;
    /* 移动端查询条件可能会更高 */
  }
}

.leftbar {
  background: rgb(250, 251, 254);
  box-shadow: 0 4px 16px 0 #5572921a;
  border-radius: 0 0px 10px 0;
  position: absolute;
  left: 0;
  top: 14px;
  width: 130px;
  transition: transform 0.3s ease-in-out;
  /* 添加过渡效果 */
  transform: translateX(-100%);
  /* 默认隐藏 */
}

.toolshow-visible {
  transform: translateX(0);
  /* 显示 */
}

.leftbar li span,
.leftbar li a {
  display: block;
  border-bottom: 1px solid #F5F6F8;
  line-height: 32px;
  font-size: 12px;
  padding: 0 10px;
}

.leftbar li span {
  color: #2A303B;
  font-weight: bold;
}

.leftbar li a {
  color: #5B6371;
  text-decoration: none;
}

.leftbarcontent {
  position: fixed;
  left: 0;
  top: 60px;
}

.zdbutton {
  width: 130px;
  display: block;
  height: 14px;
  background: #ffffff url(../../assets/image/sq.png) no-repeat 110px center;
  background-size: 13px 13px;
  cursor: pointer;
  border-radius: 0 10px 0 0;
}

.zdbutton-visible {
  width: 130px;
  display: block;
  height: 14px;
  position: relative;
  background: #ffffff;
  cursor: pointer;
  border-radius: 0 10px 0 0;
}

.zdbutton-visible::after {
  content: "";
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%) rotate(180deg);
  width: 15px;
  height: 15px;
  background: url(../../assets/image/sq.png) no-repeat center;
  background-size: 13px 13px;
}

.leftbar a:hover {
  background-image: linear-gradient(90deg, #295cff24 0%, #ffffff00 100%);
  border-left: 3px solid #295CFF
}

.leftbar a.active {
  background-image: linear-gradient(90deg, #295cff24 0%, #ffffff00 100%);
  border-left: 3px solid #295CFF
}

.leftbar a.active:hover {
  background-image: linear-gradient(90deg, #295cff24 0%, #ffffff00 100%);
  border-left: 3px solid #295CFF
}
</style>
<style>
.el-table th {
  border-color: rgba(216, 228, 240, 1) !important;
}
</style>